package com.zhanghp.class03;

import com.zhanghp.refer.ListNode;

/**
 * <h1>左神解法</h1>
 * <br/>
 * <p>左神解法就很牛，代码很清晰，而且空链表也没问题，我的会报错</p>
 * <p>再看我的代码，一看就是缝缝补补，还是有待提升...</p>
 *
 * @author zhanghp
 * @since 2023/10/20 10:40
 */
public class Code05_AddTwoNumbersZuo {
    public static void main(String[] args) {
        ListNode.printLinkedList(addTwoNumbers(null, getl2()));
    }
    public static ListNode getl2() {
        ListNode head = new ListNode(9);
        ListNode result = head;
        for (int i = 0; i < 3; i++) {
            head.next = new ListNode(9);
            head = head.next;
        }
        return result;
    }
    public static ListNode addTwoNumbers(ListNode head1, ListNode head2) {
        int len1 = listLength(head1);
        int len2 = listLength(head2);
        ListNode l = len1 >= len2 ? head1 : head2;
        ListNode s = l == head1 ? head2 : head1;
        ListNode curL = l;
        ListNode curS = s;
        ListNode last = curL;
        int carry = 0;
        int curNum = 0;
        while (curS != null) {
            curNum = curL.val + curS.val + carry;
            curL.val = (curNum % 10);
            carry = curNum / 10;
            last = curL;
            curL = curL.next;
            curS = curS.next;
        }
        while (curL != null) {
            curNum = curL.val + carry;
            curL.val = (curNum % 10);
            carry = curNum / 10;
            last = curL;
            curL = curL.next;
        }
        if (carry != 0) {
            last.next = new ListNode(1);
        }
        return l;
    }

    // 求链表长度
    public static int listLength(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
}
